package com.huluobo.a2308douyindemo.live

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.huluobo.a2308douyindemo.R
import com.huluobo.a2308douyindemo.adapter.GiftAdapter
import com.huluobo.a2308douyindemo.adapter.GoodsAdapter
import com.huluobo.a2308douyindemo.adapter.MessageAdapter
import com.huluobo.a2308douyindemo.adapter.UserIconAdapter
import com.huluobo.a2308douyindemo.bean.AccountBean
import com.huluobo.a2308douyindemo.bean.DanmakuBean
import com.huluobo.a2308douyindemo.bean.GIftBean
import com.huluobo.a2308douyindemo.bean.Gift7037Bean
import com.huluobo.a2308douyindemo.bean.MessageBean
import com.huluobo.a2308douyindemo.bean.VideoBean
import com.huluobo.a2308douyindemo.databinding.ActivityLiveBinding
import com.huluobo.a2308douyindemo.mvvm.BaseActivity
import com.huluobo.a2308douyindemo.net.Const
import com.huluobo.a2308douyindemo.shop.DetailActivity
import com.huluobo.a2308douyindemo.utils.ImageUtils
import com.huluobo.a2308douyindemo.utils.MySp
import com.huluobo.a2308douyindemo.utils.MyToast
import com.huluobo.a2308douyindemo.utils.Utils.toTime
import com.hyphenate.EMCallBack
import com.hyphenate.EMChatRoomChangeListener
import com.hyphenate.EMMessageListener
import com.hyphenate.EMValueCallBack
import com.hyphenate.chat.EMChatRoom
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMTextMessageBody
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import top.littlefogcat.danmakulib.danmaku.Danmaku
import top.littlefogcat.danmakulib.danmaku.DanmakuManager

@AndroidEntryPoint
class LiveActivity : BaseActivity<ActivityLiveBinding, LiveViewModel>() {
    private lateinit var videoBean: VideoBean
    private lateinit var giftAdapter: GiftAdapter
    private lateinit var gIftBean: Gift7037Bean
    private lateinit var accountBean: AccountBean
    private lateinit var messageAdapter: MessageAdapter
    private lateinit var userIconAdapter: UserIconAdapter
    private lateinit var goodsAdapter: GoodsAdapter

    //直播间人数
    private var currentUserCount = 1

    //声明弹幕数据源
    private val danmuList = mutableListOf<DanmakuBean>()
    override fun initData() {
        vm.getDanmaku(0, videoBean.id.toString())
        vm.focusedSuccess.observe(this) {
            binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_alpha_black)
            binding.liveFollowBtn.text = "已关注"
            MyToast.showLong("关注成功")
        }

        vm.unFocusSuccess.observe(this) {
            binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_red)
            binding.liveFollowBtn.text = "关注"
            MyToast.showLong("取消关注成功")
        }

        //发送弹幕成功时
        vm.sendDanmakuSuccess.observe(this) {
            binding.liveDanmuEt.text.clear()
            binding.liveDanmuLl.visibility = View.GONE
        }

        //获取全部弹幕成功
        vm.getDanmakuSuccess.observe(this) {
            danmuList.addAll(it.data)
        }

        //获取礼物列表成功
        vm.getGiftSuccess.observe(this) {
//            Log.e("TagA", "礼物:${it.data.size}")
        }

        vm.getGift7037Success.observe(this) {
            giftAdapter.data.clear()
            giftAdapter.data.addAll(it.data)
            giftAdapter.notifyDataSetChanged()
        }

        //修改金币成功,发送礼物
        vm.modifyCoinSuccess.observe(this) {
            sendGift()

            //上传接口
//            vm.modifyCoin(accountBean.id, (-gIftBean.price).toString())

            //保存本地
            //修改最新的余额
            accountBean.coinamount -= gIftBean.price
            //更新到sp中
            val accountJson = Gson().toJson(accountBean)
            MySp.putString(Const.KEY_ACCOUNT, accountJson)
            binding.liveUserMoneyTv.text = "${accountBean.coinamount} 抖币"
        }

        //获取商品列表成功
        vm.getGoodsInfoSuccess.observe(this) {
            goodsAdapter.data.clear()
            goodsAdapter.data.addAll(it.data)
            goodsAdapter.notifyDataSetChanged()
        }
    }

    override fun initView() {
        val json = MySp.get(Const.KEY_VIDEO)
        videoBean = Gson().fromJson(json, VideoBean::class.java)
        //通过mySp提取账户的json,转换为账户的Bean
        accountBean = Gson().fromJson(MySp.get(Const.KEY_ACCOUNT), AccountBean::class.java)

        binding.liveUserMoneyTv.text = "${accountBean.coinamount} 抖币"

        //视频播放进度
        binding.livePlayer.setGSYVideoProgressListener { progress, secProgress, currentPosition, duration ->
            //TODO 弹幕需要优化,接收实时弹幕
            danmuList.forEach {
                if (it.playtime_.toLong() == currentPosition) {
                    val danmaku = Danmaku()
                    danmaku.text = it.content
                    danmaku.size = 30
                    DanmakuManager.getInstance().send(danmaku)
                }
            }
        }

        binding.livePlayer.backButton.visibility = View.GONE
        binding.livePlayer.setUp(videoBean.videopath, true, "")

        //头像,名字,喜欢人数
        ImageUtils.loadCircleImage(this, videoBean.avatar_url, binding.liveUserIconIv)
        binding.liveUsernameTv.text = videoBean.name
        binding.liveLikeCountTv.text = "${videoBean.commentnum}人喜欢"

        //关闭按钮
        binding.liveRoomCloseIv.setOnClickListener {
            finish()
        }

        binding.liveRoomUserCountTv.text = "1人在线"

        var isFollowed = false
        binding.liveFollowBtn.setOnClickListener {
            if (isFollowed) {
                //已关注,需要出发取消关注接口
                vm.unFocusUser(MySp.getInt(Const.PARAM_USER_ID), videoBean.userid)
                isFollowed = false
            } else {
                //未关注,触发关注接口
                vm.focusedUser(MySp.getInt(Const.PARAM_USER_ID), videoBean.userid)
                isFollowed = true
            }
        }

        //给LikeView添加资源文件
        binding.liveLikeView.addLikeImages(
            R.drawable.fav_0,
            R.drawable.fav_1,
            R.drawable.fav_2,
            R.drawable.fav_3,
            R.drawable.fav_4,
            R.drawable.fav_5,
        )

        //点击点赞图标的时候
        binding.liveLikeIv.setOnClickListener {
            //触发飘心动画
            binding.liveLikeView.addFavor()
        }

        //点击弹幕按钮展示弹幕输入框
        binding.liveDanmuIv.setOnClickListener {
            binding.liveDanmuLl.visibility = View.VISIBLE
        }
//初始化弹幕布局,需要将FrameLayout填入
        DanmakuManager.getInstance().init(this, binding.liveDanmuView)
        //发送弹幕
        binding.liveDanmuSendIv.setOnClickListener {
            val danmuString = binding.liveDanmuEt.text.toString()
            if (danmuString.isNotEmpty()) {

                //生成一条弹幕
                val danmaku = Danmaku()
                danmaku.text = danmuString
                danmaku.size = 30

                DanmakuManager.getInstance().send(danmaku)

                val danmakuBean = DanmakuBean(
                    danmuString,
                    System.currentTimeMillis().toTime(),
                    0,
                    "#ff0000",
                    30,
                    0,
                    //弹幕的itemid需要是视频的id,不能使用视频的itemid,否则获取不到
                    videoBean.id.toLong(),
                    binding.livePlayer.currentPositionWhenPlaying.toString(),
                    MySp.getInt(Const.PARAM_USER_ID)
                )
                vm.sendDanmaku(danmakuBean)
            } else {
                MyToast.showLong("弹幕内容不能为空")
            }
        }

        //初始化礼物列表
        binding.liveGiftRv.layoutManager = GridLayoutManager(this, 4)
        giftAdapter = GiftAdapter()
        binding.liveGiftRv.adapter = giftAdapter

        giftAdapter.setOnItemClickListener { adapter, view, position ->
            gIftBean = giftAdapter.data[position]
            //选中礼物赋值
            ImageUtils.loadRoundImage(
                this,
                Const.BASE_URL_7015 + gIftBean.imgUrl,
                binding.liveGiftSelectIv,
                20
            )
            binding.liveGiftSelectTv.text = gIftBean.title
        }

        //礼物布局展示
        binding.liveGiftIv.setOnClickListener {
            binding.liveGiftCl.visibility = View.VISIBLE
            //加载礼物数据源
            vm.getGift()
            vm.getGift7037()
        }

        binding.liveGiftCloseTv.setOnClickListener {
            binding.liveGiftCl.visibility = View.GONE
        }

        binding.liveGiftSendTv.setOnClickListener {
            //发送礼物之前需要验证余额是否充足
            if (gIftBean.price > accountBean.coinamount) {
                MyToast.showLong("余额不足清充值")
                return@setOnClickListener
            }
            //余额充足,减掉礼物金币,发起请求 1200
            vm.modifyCoin(accountBean.id, (-gIftBean.price).toString())
        }

        //跳转充值页面
        binding.livePayBtn.setOnClickListener {
            startAct(PayActivity::class.java)
        }

        //初始化聊天布局
        binding.liveChatRoomRv.layoutManager = LinearLayoutManager(this)
        messageAdapter = MessageAdapter()
        binding.liveChatRoomRv.adapter = messageAdapter

        //点击聊天文本,展示聊天框
        binding.liveInputTv.setOnClickListener {
            binding.liveChatRoomLl.visibility = View.VISIBLE
        }

        //点击聊天发送按钮
        binding.liveChatRoomSendIv.setOnClickListener {
//            val messageBean = MessageBean(MySp.get(Const.PARAM_USERNAME), binding.liveChatRoomEt.text.toString())
//            messageAdapter.data.add(messageBean)
//            messageAdapter.notifyDataSetChanged()
            sendMessage()
        }

        initChatRoom()

        //聊天室人员Rv初始化
        binding.liveRoomUserRv.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        userIconAdapter = UserIconAdapter()
        binding.liveRoomUserRv.adapter = userIconAdapter

        userIconAdapter.data.add(MySp.get(Const.KEY_USER_ICON))
        userIconAdapter.notifyDataSetChanged()

        //初始化小黄车布局
        binding.liveCartRv.layoutManager = GridLayoutManager(this, 2)
        goodsAdapter = GoodsAdapter()
        binding.liveCartRv.adapter = goodsAdapter


        binding.liveCartIv.setOnClickListener {
            //展示小黄车布局
            showCart()
        }

        binding.liveCartCloseIv.setOnClickListener {
            closeCart()
        }

        //小黄车列表的点击事件
        goodsAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(this, DetailActivity::class.java)
            intent.putExtra(Const.KEY_GOODS_ID, goodsAdapter.data[position].id)
            startActivity(intent)
        }
    }

    //关闭小黄车
    private fun closeCart() {
        val animOut = AnimationUtils.loadAnimation(this, R.anim.anim_out)
        animOut.duration = 500
        animOut.interpolator = AccelerateInterpolator()
        animOut.setAnimationListener(object : AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
            }

            override fun onAnimationEnd(animation: Animation?) {
                binding.liveCartCl.visibility = View.GONE
            }

            override fun onAnimationRepeat(animation: Animation?) {
            }
        })
        binding.liveCartCl.startAnimation(animOut)
    }

    //展示小黄车布局
    private fun showCart() {
        //加载小黄车商品数据
        vm.getGoodsInfo(0, 1, 10)
        binding.liveCartCl.visibility = View.VISIBLE
        val animIn = AnimationUtils.loadAnimation(this, R.anim.anim_in)
        animIn.duration = 500
        animIn.interpolator = AccelerateInterpolator()
        binding.liveCartCl.startAnimation(animIn)
    }

    //聊天室发送消息
    private fun sendMessage() {
        val content = binding.liveChatRoomEt.text.toString()
        if (content.isNotEmpty()) {
            val emMessage = EMMessage.createTextSendMessage(content, Const.CHAT_ROOM_ID)
            emMessage.chatType = EMMessage.ChatType.ChatRoom
            EMClient.getInstance().chatManager().sendMessage(emMessage)
            emMessage.setMessageStatusCallback(object : EMCallBack {
                override fun onSuccess() {
                    //切换到主线程,刷新适配器
                    runBlocking(Dispatchers.Main) {
                        //消息发送成功的时候,刷新适配器
                        val messageBean = MessageBean(EMClient.getInstance().currentUser, content)
                        messageAdapter.data.add(messageBean)
                        messageAdapter.notifyDataSetChanged()
                        scrollToEnd()
                        binding.liveChatRoomEt.text.clear()
                        binding.liveChatRoomLl.visibility = View.GONE
                    }
                }

                override fun onError(code: Int, error: String?) {
                }
            })
        } else {
            binding.liveChatRoomEt.error = "不要发送空消息"
        }
    }

    //让聊天记录滚动到最下方
    private fun scrollToEnd() {
        if (messageAdapter.data.size > 1) {
            binding.liveChatRoomRv.scrollToPosition(messageAdapter.data.size - 1)
        }
    }

    //接受消息的监听器
    private val messageListener = EMMessageListener {
        runBlocking(Dispatchers.Main) {
            it.forEach { emMessage ->
                val messageBean = MessageBean(emMessage.from, (emMessage.body as EMTextMessageBody).message)
                messageAdapter.data.add(messageBean)
                messageAdapter.notifyDataSetChanged()
                scrollToEnd()
            }
        }
    }

    //初始化聊天室
    private fun initChatRoom() {
        //添加消息监听器
        EMClient.getInstance().chatManager().addMessageListener(messageListener)
        //初始化加入聊天室
        EMClient.getInstance().chatroomManager().joinChatRoom(Const.CHAT_ROOM_ID, object : EMValueCallBack<EMChatRoom> {
            override fun onSuccess(value: EMChatRoom?) {
                runBlocking(Dispatchers.Main) {
                    messageAdapter.data.add(
                        MessageBean(
                            "系统",
                            "欢迎来到直播间!抖音严禁未成年人直播或魁梧消费.严禁出现违法违规,低俗色情,吸烟酗酒,人身伤害等直播内容.理性消费,如主播在直播中以不当方式诱导打赏,请谨慎辨别.切勿私下交易,以防止人身财产损失,谨防网络诈骗.实际下载应用以明示信息为准"
                        )
                    )
                    messageAdapter.notifyDataSetChanged()
                }
            }

            override fun onError(error: Int, errorMsg: String?) {
                Log.e("TagA", "加入聊天室失败:$error,msg:$errorMsg")
            }
        })
        //添加聊天室事件监听器
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomListener)
    }

    //监听聊天室事件,主要为了获取用户加入和退出
    private val chatRoomListener = object : EMChatRoomChangeListener {
        override fun onChatRoomDestroyed(roomId: String?, roomName: String?) {
        }

        override fun onMemberJoined(roomId: String?, participant: String?) {
            runBlocking(Dispatchers.Main) {
                messageAdapter.data.add(
                    MessageBean(
                        "系统",
                        "${participant}加入直播间"
                    )
                )
                messageAdapter.notifyDataSetChanged()
                currentUserCount++
                binding.liveRoomUserCountTv.text = "${currentUserCount}人在线"
                userIconAdapter.data.add(MySp.get(Const.KEY_USER_ICON))
                userIconAdapter.notifyDataSetChanged()
            }
        }

        override fun onMemberExited(roomId: String?, roomName: String?, participant: String?) {
            runBlocking(Dispatchers.Main) {
                messageAdapter.data.add(
                    MessageBean(
                        "系统",
                        "${participant}退出直播间"
                    )
                )
                currentUserCount--
                binding.liveRoomUserCountTv.text = "${currentUserCount}人在线"
                messageAdapter.notifyDataSetChanged()
                userIconAdapter.data.removeAt(userIconAdapter.data.size - 1)
                userIconAdapter.notifyDataSetChanged()
            }
        }

        override fun onRemovedFromChatRoom(reason: Int, roomId: String?, roomName: String?, participant: String?) {
        }

        override fun onMuteListAdded(chatRoomId: String?, mutes: MutableList<String>?, expireTime: Long) {
        }

        override fun onMuteListRemoved(chatRoomId: String?, mutes: MutableList<String>?) {
        }

        override fun onWhiteListAdded(chatRoomId: String?, whitelist: MutableList<String>?) {
        }

        override fun onWhiteListRemoved(chatRoomId: String?, whitelist: MutableList<String>?) {
        }

        override fun onAllMemberMuteStateChanged(chatRoomId: String?, isMuted: Boolean) {
        }

        override fun onAdminAdded(chatRoomId: String?, admin: String?) {
        }

        override fun onAdminRemoved(chatRoomId: String?, admin: String?) {
        }

        override fun onOwnerChanged(chatRoomId: String?, newOwner: String?, oldOwner: String?) {
        }

        override fun onAnnouncementChanged(chatRoomId: String?, announcement: String?) {
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //页面销毁时,退出聊天室
        EMClient.getInstance().chatroomManager().leaveChatRoom(Const.CHAT_ROOM_ID)
        //移除2个监听器
        EMClient.getInstance().chatManager().removeMessageListener(messageListener)
        EMClient.getInstance().chatroomManager().removeChatRoomListener(chatRoomListener)
    }

    //发送礼物
    private fun sendGift() {
        //创建一个礼物的图片view
        val giftImageView = ImageView(this)
        //一个直接new出来的View是没有宽高的,需要手动设置宽高
        //设置的时候提供的ConstraintLayout,需要是ImageView想要展示在哪个布局上,就用哪个的LayoutParams
        val params = ConstraintLayout.LayoutParams(200, 200)
//        val params = LinearLayout.LayoutParams(200, 200)
        //设置宽高到View上
        giftImageView.layoutParams = params

        //添加View到布局上
        binding.liveRootCl.addView(giftImageView)
        //给ImageView赋值图片
        ImageUtils.loadImage(this, Const.BASE_URL_7015 + gIftBean.imgUrl, giftImageView)

        //获取rootCl的宽高
        val screenWidth = binding.liveRootCl.measuredWidth
        val screenHeight = binding.liveRootCl.measuredHeight

        //Y轴动画
        val translationY = ObjectAnimator.ofFloat(
            giftImageView,
            "translationY",
            screenHeight.toFloat(),
            (screenHeight / 3 * 2).toFloat(),
            (screenHeight / 4).toFloat(),
            (screenHeight / 2).toFloat(),
            (screenHeight / 5 * 3).toFloat(),
            (screenHeight / 2).toFloat(),
        )

        //X轴动画
        val translationX = ObjectAnimator.ofFloat(
            giftImageView,
            "translationX",
            (screenWidth / 2).toFloat(),
            (screenWidth / 5).toFloat(),
            (screenWidth / 3 / 2).toFloat(),
            (screenWidth / 2).toFloat(),
            (screenWidth / 2).toFloat(),
            (screenWidth / 3).toFloat(),
        )

        val rotation = ObjectAnimator.ofFloat(giftImageView, "rotation", 0f, 1800f)
        val scaleX = ObjectAnimator.ofFloat(giftImageView, "scaleX", 1f, 2f, 3f, 2f, 1f)
        val scaleY = ObjectAnimator.ofFloat(giftImageView, "scaleY", 1f, 2f, 3f, 2f, 1f)
        val alpha = ObjectAnimator.ofFloat(giftImageView, "alpha", 1f, 1f, 1f, 1f, 1f, 0f)

        val animatorSet = AnimatorSet()
        animatorSet.duration = 3000
        animatorSet.playTogether(translationX, translationY, rotation, scaleX, scaleY, alpha)
        animatorSet.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                //当动画结束时,隐藏掉礼物ImageView
                binding.liveRootCl.removeView(giftImageView)
            }

            override fun onAnimationStart(animation: Animator) {
                super.onAnimationStart(animation)
                //当动画开始时,隐藏掉礼物布局
                binding.liveGiftCl.visibility = View.GONE
            }
        })
        animatorSet.start()
    }
}